package com.christian.thread.safe;

import sun.jvm.hotspot.utilities.soql.JSJavaVM;

import java.util.concurrent.TimeUnit;

/**
 * 文件描述：需求现在有100张火车票，有两个窗口同时抢火车票，请使用多线程模拟抢票效果。
 *
 * @Author：wang
 * @Date：2020-01-19 22:45:32
 */
public class GrabVotes {

    /**
     * 总票数
     */
    private static int totalVotes = 100;

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            while (totalVotes > 0) {
                try {
                    //睡眠50毫秒
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //开始买票
                sale();
            }
        }, "1号窗口");

        Thread t2 = new Thread(() -> {
            while (totalVotes > 0) {
                try {
                    //睡眠50毫秒
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //开始买票
                sale();
            }
        }, "2号窗口");

        //启动线程
        t1.start();
        t2.start();
    }


    /**
     * 售票
     */
    public static void sale() {
        if (totalVotes > 0) {
            System.out.println(Thread.currentThread().getName() + "：出售第 " + (100 - totalVotes + 1) + " 张票");
            totalVotes--;
        }
    }
}
